package com.dongrj.framework.starter.log.property;


import com.dongrj.framework.core.utils.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public final class PropertiesReader {
    private static final Properties CONFIG = new Properties();
    private static boolean isLoaded = false;

    public static final String CONFIG_FILE = "META-INF/appconfig.properties";

    /**
     * 读取 /META-INF/appconfig.properties 配置文件内容，带缓存
     *
     * @return Properties 对象，包含配置文件中的键值对；如果发生异常，返回空的 Properties 对象
     */
    public static Properties readConfig() {
        if (isLoaded) {
            return CONFIG;
        }
        try (InputStream inputStream = PropertiesReader.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) {
            if (inputStream == null) {
                System.err.println("无法找到配置文件:" + CONFIG_FILE);
                return new Properties();
            }
            synchronized (CONFIG) {
                CONFIG.load(inputStream);
                isLoaded = true;
            }
        } catch (IOException e) {
            System.err.println("读取配置文件失败: " + e.getMessage());
            return new Properties();
        }
        return CONFIG;
    }

    public static String getProperty(String key) {
        return readConfig().getProperty(key);
    }

    public static String getAppName() {
        return getProperty("app.name");
    }

    public static String getAppModule() {
        return getProperty("app.module");
    }

    public static String getAppId() {
        String appId = getProperty("app.id");
        if (StringUtils.isEmpty(appId)) {
            return String.format("%s-%s", getAppName(), getAppModule());
        }
        return appId;
    }
}